//
//  FlightBookController.m
//  ELife
//
//  Created by xiaozhi on 11-5-26.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FlightBookController.h"
#import "StepView.h"
#import "UIViewUtil.h"
#import "FlightCustomerController.h"
#import "ELifeAppDelegate.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "FlightCustomerModel.h"
#import "FlightContactController.h"
#import "FlightAddressController.h"
#import "GetMyData.h"
#import "LoginController.h"
#import "FlightExplainController.h"
#import "FlightCheckedController.h"
#import "FlightSearchController.h"

@implementation FlightBookController
@synthesize radioButton1, radioButton2, radioButton3, contactNameLabel, contactPhoneLabel, addressNameLabel, addressPcodeLabel, addressPhoneLabel, addressAddressLabel;

- (void)updateContact:(FlightContactModel *)contactModel
{
    [contactNameLabel setText:contactModel.name];
    [contactPhoneLabel setText:contactModel.phone];
}

- (void)updateAddress:(FlightAddressModel *)addressModel
{
    [addressNameLabel setText:addressModel.name];
    [addressPhoneLabel setText:addressModel.phone];
    [addressPcodeLabel setText:addressModel.pCode];
    [addressAddressLabel setText:addressModel.address];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [_addressModel release];
    [_contactModel release];
    [_customerList release];
    [radioButton1 release];
    [radioButton2 release];
    [radioButton3 release];
    [contactNameLabel release];
    [contactPhoneLabel release];
    [addressNameLabel release];
    [addressPcodeLabel release];
    [addressPhoneLabel release];
    [addressAddressLabel release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle
// 填充联系人视图 并且返回新的Y坐标
- (NSInteger)fillCustomerView:(FlightCustomerModel *)model 
          inCustomerView:(UIView *)customerView
               atYOffset:(NSInteger)y
{
    // 登机人信息的子视图
    NSArray *childViewList = [[NSBundle mainBundle]loadNibNamed:
                              @"FlightBookChildView" owner:self options:nil];
    UIView *childView = [childViewList objectAtIndex:0];
    
    UILabel *nameLabel = (UILabel *)[childView viewWithTag:1];
    UILabel *idLabel = (UILabel *)[childView viewWithTag:2];
    UILabel *priceLabel = (UILabel *)[childView viewWithTag:3];
    
    [nameLabel setText:model._user_name];
    [idLabel setText:model._certificate_num];
    [priceLabel setText:[NSString stringWithFormat:@"%@元", model._insurance_price]];
    
    NSInteger customerHei = childView.frame.size.height;
    
    [customerView addSubview:childView];
       
    childView.frame = CGRectMake(customerView.frame.origin.x, y, childView.frame.size.width, childView.frame.size.height);
    
    customerView.frame = CGRectMake(customerView.frame.origin.x, customerView.frame.origin.y, customerView.frame.size.width, customerView.frame.size.height + customerHei);
    
    return y + customerHei;
}

// 在这里加载所有view 到一个scrollView
- (void)initViews
{
    const NSInteger OFFSET_Y = 5;
    const NSInteger OFFSET_X = 10;
//    CGFloat parentWid = self.view.frame.size.width;
//    CGFloat parentHei = self.view.frame.size.height;
    
    UIScrollView *scrollView = [[UIScrollView alloc]initWithFrame:self.view.frame];
    scrollView.backgroundColor = [UIViewUtil getCommonBg];
    StepView *stepView = [[StepView alloc] createStepViewWithStep:2];
    [scrollView addSubview:stepView];
    [stepView release];
    
    NSInteger y = stepView.frame.origin.y + stepView.frame.size.height + OFFSET_Y;
    
    NSArray *viewList = [[NSBundle mainBundle]loadNibNamed:
                         @"FlightBookController" owner:self options:nil];
    
    // load all child view from nib to scrollView
    for (UIView *child in viewList) {
        // 不要加入自己
        if (child == self.view) {
            continue;
        }
        [UIViewUtil viewRoundFrame:child];
        
        // 处理登机人信息视图
        if (child.tag == TAG_CUSTOMER_VIEW) {
            NSInteger customerY = y;
            for (NSInteger customerIndex = 0; customerIndex < [_customerList count]; customerIndex++) {
                FlightCustomerModel *model = [_customerList objectAtIndex:customerIndex];
                customerY = [self fillCustomerView:model 
                        inCustomerView:child
                             atYOffset:customerY];
            }
        }
        
        NSInteger hei = child.frame.size.height;
        if (child.tag == TAG_CUSTOMER_VIEW) hei += 10;
        
        
        [child setFrame:CGRectMake(OFFSET_X, y, child.frame.size.width, hei)];
        y += (hei + OFFSET_Y);
        
        [scrollView addSubview:child];
    }
    
    [scrollView setContentSize:CGSizeMake(self.view.frame.size.width - 2 * OFFSET_X, y)];
    [self.view addSubview:scrollView];
    [scrollView release];
    
    needAddress = NO;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIViewUtil getCommonBg];
    [self requestCustomerList];    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


#pragma mark - network
// 请求登机人信息
- (void)requestCustomerList
{
    NSString* userid = [GetMyData getUserId];
    
    if (userid == nil) {
        LoginController* lc = [[LoginController alloc] init:self];
        [self.navigationController pushViewController:lc animated:YES];
        [lc release];
        return;
    }

    
    ELifeAppDelegate *app = [ELifeAppDelegate App];
    [app showProgressDialog:@"请稍候"];
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"airline.php"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:1];
    [param setObject:@"get_air_userinfo_by_user_id" forKey:@"action"];
    [param setObject:userid forKey:@"user_id"];
    [param setObject:@"300" forKey:@"limit"]; // 不需要分页现实 所以limit传大一些
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"requestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];

}

- (void)requestFinished:(NSData *)response
{
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    GDataXMLElement* rootElement = [doc rootElement];
    NSLog(@"--------rootElement:%@", rootElement);
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    //    NSLog(@"--------body:%@", bodyElement);
    GDataXMLElement *infos = [[bodyElement elementsForName:@"airuserinfos"]objectAtIndex:0];
    //某个具体节点的文本内容
    NSArray* customerList = [infos elementsForName:@"airuserinfo"];
    NSLog(@"--------customer_list:%@", customerList);
    
    _customerList = [[NSMutableArray alloc] initWithCapacity:[customerList count]];
    
    for (NSInteger index = 0; index < [customerList count]; index++) {
        GDataXMLElement *item = [customerList objectAtIndex:index];
        
        FlightCustomerModel *customerModel = [[FlightCustomerModel alloc] init];
        
        /*info_id = 登机人信息id
		user_id = 用户id
		user_name = 登机人姓名
		enger_type = 登机人类型
		certificate_type = 证件类型  （身份证/护照）
		certificate_num = 证件号码 
		insurance_number = 保险份数   1-5份   
		insurance_price = 保险金额
		phone = 登机人电话
		birthday = 登机人出生日期
         */
        
        customerModel._info_id = [[[item elementsForName:@"info_id"]objectAtIndex:0]stringValue];
        customerModel._user_id = [[[item elementsForName:@"user_id"]objectAtIndex:0]stringValue];
        customerModel._user_name = [[[item elementsForName:@"user_name"]objectAtIndex:0]stringValue];
        customerModel._enger_type = [[[item elementsForName:@"enger_type"]objectAtIndex:0]stringValue];
        customerModel._certificate_type = [[[item elementsForName:@"certificate_type"]objectAtIndex:0]stringValue];
        customerModel._certificate_num = [[[item elementsForName:@"certificate_num"]objectAtIndex:0]stringValue];
        customerModel._insurance_number = [[[item elementsForName:@"insurance_number"]objectAtIndex:0]stringValue];
        customerModel._insurance_price = [[[item elementsForName:@"insurance_price"]objectAtIndex:0]stringValue];
        customerModel._phone = [[[item elementsForName:@"phone"]objectAtIndex:0]stringValue];
        customerModel._birthday = [[[item elementsForName:@"birthday"]objectAtIndex:0]stringValue];
        
        [_customerList addObject:customerModel];
    }
    
    [doc release];
    
    [self initViews];
    [[ELifeAppDelegate App] hideProgressDialog];
}

#pragma markend

// 添加登机人
- (IBAction)addCustomer
{
    FlightCustomerController *nextController = [[FlightCustomerController alloc]initWithNibName:@"FlightCustomerController" bundle:nil];
    
    // 传递登机人列表
    nextController._customerList = _customerList;
    
    [self.navigationController pushViewController:nextController animated:YES];
    [nextController release];
}


// 添加联系人
- (IBAction)addContact
{
    FlightContactController *nextController = [[FlightContactController alloc]initWithNibName:@"FlightContactController" bundle:nil];
    
    // 传递contact
    [nextController setFlightContactModel:_contactModel target:self backAction:@selector(editContactBack:)];
    
    [self.navigationController pushViewController:nextController animated:YES];
    [nextController release];

}

- (void)editContactBack:(FlightContactModel *)contactModel
{
    [_contactModel release];
    _contactModel = [contactModel retain];
    [self updateContact:_contactModel];
}

- (void)pickSenderType:(id)sender
{
        
    [radioButton1 setImage:[UIImage imageNamed:@"radiobutton_unselected.png"] 
            forState:UIControlStateNormal];
    [radioButton2 setImage:[UIImage imageNamed:@"radiobutton_unselected.png"] 
                  forState:UIControlStateNormal];

    [radioButton3 setImage:[UIImage imageNamed:@"radiobutton_unselected.png"] 
                  forState:UIControlStateNormal];

    
    UIButton *selectedButton = (UIButton *)sender;
    [selectedButton setImage:[UIImage imageNamed:@"radiobutton_selected.png"]
                    forState:UIControlStateNormal];
    
    needAddress = NO;
    if (selectedButton == radioButton2) {
        needAddress = YES;
    }
}

- (void)showInfo
{
    FlightExplainController *nextControl = [[FlightExplainController alloc] initWithImageList:[NSArray arrayWithObjects:[UIImage imageNamed:@"explain_address.jpg"], [UIImage imageNamed:@"explain_changeticket.jpg"], nil]];
    
    [self.navigationController pushViewController:nextControl animated:YES];
    
    [nextControl release];
}

- (void)showAlertView:(NSString *)msg
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alertView show];
    [alertView release];
}

// 添加配送但地址
- (void)addAddress
{
    if (needAddress == NO) {
        [self showAlertView:@"您选择的配送方式不需要填写配送单地址"];
        return;
    }
    
    FlightAddressController *nextController = [[FlightAddressController alloc] initWithAddressModel:_addressModel withTarget:self withBackAction:@selector(addAddressBack:)];
    [self.navigationController pushViewController:nextController animated:YES];
    [nextController release];
}

- (void)addAddressBack:(FlightAddressModel *)addressModel
{
    NSLog(@"retainCount:%d", [_addressModel retainCount]);
    [_addressModel release];
    
    NSLog(@"retainCount:%d", [_addressModel retainCount]);
    
    _addressModel = [addressModel retain];
    
    NSLog(@"retainCount:%d", [_addressModel retainCount]);
    [self updateAddress:_addressModel];
}

- (void)nextStep
{
    if (_contactModel == nil
        || (needAddress == YES && _addressModel == nil)
        || [_customerList count] == 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"请您将信息填写完整" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        [alertView release];
        return;
    }
    
    [FlightSearchController getCheckedModel].customerList = _customerList;
    [FlightSearchController getCheckedModel].contactModel = _contactModel;
    [FlightSearchController getCheckedModel].addressModel = _addressModel;
    
    FlightCheckedController *nextControlller = [[FlightCheckedController alloc] initWithCheckedModel:[FlightSearchController getCheckedModel]];
    [self.navigationController pushViewController:nextControlller animated:YES];
    [nextControlller release];
    
}

@end
